import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:liuxlcommon/util/toast_util.dart';
import 'package:love_newf/app/com/base/L.dart';
import 'package:love_newf/app/com/model/live_result_plugin_model.dart';
import 'package:love_newf/app/com/model/room_info_model.dart';
import 'package:love_newf/app/page/live/live_logic.dart';

class LiveMessagePlugin {
  static const BasicMessageChannel<dynamic> _channel =
      BasicMessageChannel('LiveMessagePlugin', StandardMessageCodec());

  static var zegoInitSuccess = false;
  static var beautyInitSuccess = true;

  static init() {
    Future.delayed(const Duration(seconds: 2)).then((v) {
      //延时两秒创建监听，之前出现过问题
      _channel.setMessageHandler((message) async {});
    });
  }

  ///zego 初始化
  static get zegoInit async {
    var appconfig = await L.appConfig;
    var l = toLiveRPModel(
        await sendMessage("zegoInit", json.encode(appconfig.toJson())));
    if (l?.code == 0) {
      zegoInitSuccess = true;
    } else {
      zegoInitSuccess = false;
      EasyLoading.showError(l?.msg ?? "${l?.code}");
    }
  }

  static get refreshMaiInfo async {
    var logic = LiveLogic.logic;
    if (logic?.roomData == null) return;
    var l = toLiveRPModel(await sendMessage(
        "refreshMaiInfo", json.encode(logic?.roomData?.toJson())));
    if (l?.code == 0) {
    } else {
      EasyLoading.showError(l?.msg ?? "${l?.code}");
    }
  }

  ///美颜主持
  static get beautyInit async {
    var appconfig = await L.appConfig;
    await sendMessage("beautyInit", json.encode(appconfig.toJson()));
    zegoInitSuccess = true;
  }

  static Future<LiveResultPluginModel?> logoutRoom() async {
    return toLiveRPModel(await sendMessage("logoutRoom", ""));
  }

  static Future<LiveResultPluginModel?> loginRoom(RoomInfoModel info) async {
    info.selfUserId = L.userInfo.userId;
    return toLiveRPModel(
        await sendMessage("loginRoom", json.encode(info.toJson())));
  }

  ///开始推拉流，并预览,默认全部麦位
  static startPreview() async {
    await sendMessage("startPreview", "");
  }

  ///退出房间，释放内存
  static exitRoom() async {
    await sendMessage("exitRoom", "");
  }

  static sendMessage(String method, String data,
      {String? action, String? viewId}) async {
    return _channel.send({
      "method": method,
      "action": action,
      "viewId": viewId,
      "data": data,
    });
  }

  static LiveResultPluginModel? toLiveRPModel(String? value) {
    if (value == null) return null;
    Map result = json.decode(value);
    var l = LiveResultPluginModel();
    l.msg = result["msg"] ?? "";
    l.code = result["code"] ?? 0;
    l.errorCode = result["errorCode"] ?? 0;
    return l;
  }
}
